package org.zoomdev.zoom.serializer.impl;

import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.common.io.Io;
import org.zoomdev.zoom.serializer.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class DefaultSerializer implements Serializer {

    public static final Serializer SERIALIZER = new DefaultSerializer();

    @Override
    public Object deserialize(byte[] src) {
        if (src == null) {
            return null;
        }

        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new ByteArrayInputStream(src));
            return ois.readObject();
        } catch (Exception e) {
            return null;
        } finally {
            Io.close(ois);
        }

    }

    @Override
    public byte[] serialize(Object data) {
        if (data == null) {
            return null;
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(data);
            oos.close();
            return os.toByteArray();
        } catch (Exception e) {
            throw new ZoomException("序列化数据失败", e);
        }
    }
}
